package ws.very.web.adptor

import java.util.HashMap
import java.util.UUID
import ws.very.util.lang.ThreadConverter
import ws.very.util.lang.Threads
import scala.collection.convert.WrapAsScala

class ApiSessionMap extends HashMap[String, Object] with SessionMap {
  var lastTime = System.currentTimeMillis //FIXME:ops需要更新
  val key: UUID = null
}

object ApiSessionMapMsg extends ThreadConverter with WrapAsScala {
  private val map = new HashMap[UUID, ApiSessionMap]
  def get(key: String) = {
    val v = if (key == null) null else map.get(UUID.fromString(key))
    if (v == null) new ApiSessionMap else {
      v.lastTime = System.currentTimeMillis
      v
    }
  }

  def apply() = {
    val nkey = UUID.randomUUID()
    val v = new ApiSessionMap {
      override val key = nkey
    }
    map.put(nkey, v)
    v
  }

  private var exitToken = false
  Runtime.getRuntime().addShutdownHook {
    exitToken = true
  }
  Threads {
    while (!exitToken) {
      val now = System.currentTimeMillis - 30 * 60 * 1000 //五分钟生命周期

      map.filter {
        case (key, value) =>
          value.lastTime < now
      }.foreach {
        case (k, v) =>
          map.remove(k)
        //println(s"apiSessionMap remove $k")
      }

      this.synchronized {
        this.wait(2000)
      }
    }
  }

}